package com.lhl.forum.controller;

import com.lhl.forum.common.AppResult;
import com.lhl.forum.common.ResultCode;
import com.lhl.forum.config.AppConfig;
import com.lhl.forum.model.User;
import com.lhl.forum.service.IUserService;
import com.lhl.forum.utils.MD5Util;
import com.lhl.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//对Controller进行API说明
@Api(tags = "用户接口")
@Slf4j
//返回数据
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 用户密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @ApiOperation("用户注册" )
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){

        //校验两次输入的密码是否相同
        if (!password.equals(passwordRepeat)){
            //打印日志
            log.warn( ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode. FAILED_TWO_PWD_NOT_SAME);
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        //盐
        String salt = UUIDUtil.UUID_32();

        //加盐后的密码
        String encryptionPw = MD5Util.md5Salt(password, salt);
        user.setSalt(salt);
        user.setPassword(encryptionPw);

        userService.createNormaUser(user);

        return AppResult.success(ResultCode.SUCCESS);
    }

    @ApiOperation("用户登录" )
    @PostMapping("/login" )
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password, HttpSession httpSession){
        User user = userService.login(username,password);;
        //非空校验
        if (user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //将登录用户加入到session的作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);

        //返回结果
        return AppResult.success();

    }

    @ApiOperation("查询用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                      @ApiParam("用户ID") @RequestParam(name = "id",required = false) Long id){
        User user = null;
        //用户Id为空，在session中拿到用户信息
        if (id == null){
            HttpSession session = request.getSession(true);
            //从session中获取当前用户信息
            user = (User)session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //用户id不为空，去数据库中拿到用户信息
            user = userService.selectById(id);
        }

        //判断查询到的用户是否存在
        if (user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS .toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS );
        }

        //返回成功查询到的结果
        return AppResult.success(user);
    }

    @ApiOperation("退出")
    @PostMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取当前用户的session
        HttpSession session = request.getSession(false);//没有则不创建
        //判断session是否为空
        if (session != null){
            //打印日志
            log.info("退出成功");
            //在登录状态下退出
            session.invalidate();

        }
        //返回结果
        return AppResult.success("退出成功");
    }
}
